package com.tarena.practice.web.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tarena.practice.common.service.HttpClientService;
import com.tarena.practice.common.vo.HttpResult;
import com.tarena.practice.common.vo.SysResult;
import com.tarena.practice.web.mapper.UserMapper;
import com.tarena.practice.web.pojo.User;
import com.tarena.practice.web.util.MailUtils;
@Service
public class UserService {
	@Autowired
	private HttpClientService client;
	
	@Autowired
	private UserMapper userMapper;
	/*
	 * web项目注册
	 */
		public void doRegister(User user) throws Exception{
			user.setCreated(new Date());
			user.setUpdated(user.getCreated());
			user.setStatus(0);
			String md5pw = DigestUtils.md5Hex(user.getPassword());
			user.setPassword(md5pw);
			userMapper.insertUser(user);
			System.out.println(user);
			MailUtils.activateMail(user);// 发送邮件到用户邮箱
		}
	
	public static final ObjectMapper mapper=new ObjectMapper();
	/*
	 * 获取票，单点登录数据转发到SSO
	 */
	public String doLogin(User user) throws Exception {
		//传参给sso
		String url ="http://sso.ldd.com/user/login";
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("u", user.getUsername());
		params.put("p", user.getPassword());
		HttpResult result = client.doPost(url,params);
		String jsonData = result.getBody();//获取sysresult的字符串其中data属性保存这ticket
		SysResult sysResult = mapper.readValue(jsonData, SysResult.class);
		String ticket=(String)sysResult.getData();
		return ticket;
	}
	
	/*
	 * 验证用户名是否存在
	 * 需要连接数据库
	 */
	public Boolean checkUsername(String username) {
		boolean isHave=false;
		int count=userMapper.checkUsername(username);
		if(count>0){
			isHave=true;
		}
		return isHave;
	}

	public void activeByUsernameAndEmail(String username, String email) {
		userMapper.activeByUsernameAndEmail(username,email);
		
	}
}
